package com.xh.easyretry.common.result;

import lombok.Data;

import java.util.Objects;
import java.util.Optional;

@Data
public class CommonResult<T> implements BaseResult {

    private Integer code;
    private String errMsg;
    private T data;

    private CommonResult() {
    }

    public CommonResult(Integer code) {
        this.code = code;
    }

    private CommonResult(Integer code, String errMsg) {
        this.code = code;
        this.errMsg = errMsg;
    }

    private CommonResult(Integer code, String errMsg, T data) {
        this.code = code;
        this.errMsg = errMsg;
        this.data = data;
    }

    public static <T> CommonResult<T> success() {
        return new CommonResult<>(CommonResultCode.SUCCESS);
    }

    public static <T> CommonResult<T> success(T data) {
        return new CommonResult<>(CommonResultCode.SUCCESS, null, data);
    }

    public static <T> CommonResult<T> fail(Integer code, String errMsg) {
        return new CommonResult<>(Optional.ofNullable(code).orElse(CommonResultCode.DEFAULT_FAIL), errMsg);
    }

    @Override
    public Integer getCode() {
        return this.code;
    }

    @Override
    public boolean isSuccess() {
        if (Objects.isNull(this.getCode())) {
            return false;
        }
        return Objects.equals(this.getCode(), CommonResultCode.SUCCESS);
    }
}
